/**
 * 
 */
package com.dalonedrow.pooled;

import java.util.ArrayList;

/**
 * @author Donald
 *
 */
public class StringListPool {
	/** the one and only instance of the <code>StringListPool</code> class. */
	private static StringListPool	instance;
	/**
	 * Gives access to the singleton instance of {@link StringListPool}.
	 * @return {@link StringListPool}
	 */
	public static StringListPool getInstance() {
		if (StringListPool.instance == null) {
			StringListPool.instance = new StringListPool(5);
		}
		return StringListPool.instance;
	}
	private ArrayList<Boolean>					locked;
	private ArrayList<PooledArrayList<String>>	pool;
	private StringListPool(final int initialCapacity) {
		// create an initial list
		pool = new ArrayList<PooledArrayList<String>>(initialCapacity);
		locked = new ArrayList<Boolean>(initialCapacity);
		// populate the list and set all items to unlocked
		for (int i = 0; i < initialCapacity; i++) {
			pool.add(new PooledArrayList<String>(i));
			locked.add(false);
		}
	}
	public PooledArrayList<String> getList() {
		int freeIndex = 0;
		for (; freeIndex < locked.size(); freeIndex++) {
			// current index is free
			if (!locked.get(freeIndex)) {
				// lock this item
				locked.set(freeIndex, true);
				break;
			}
		}
		if (freeIndex >= locked.size()) {
			// we got here because all items are in use
			// create a new item and add it to the list
			pool.add(new PooledArrayList<String>(freeIndex));
			// lock the item
			locked.add(true);
		}
		// return the item at the free index
		return pool.get(freeIndex);
	}
	public void returnObject(PooledArrayList<String> list) {
		// tell the item it's been returned to the pool
		list.returnToPool();
		// remove the lock
		locked.set(list.getPoolIndex(), false);
	}
}
